import axios from 'axios'
import Cookies from 'js-cookie'
import {Dialog,Notify} from "vant";
import Router from '@/router/index'
// create an axios instance
const service = axios.create({
  //baseURL: "http://121.199.34.222:8081/cscdc_hrtrain", // url = base url + request url
  baseURL:process.env.VUE_APP_BASE_URL,
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000, // request timeout
  headers:{"Content-Type":"application/json;"},
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (typeof (config.data) == "undefined"){
      config.data = {};
    }
    config.headers['X-Access-Token'] = Cookies.get('kaoShi_token')
    return config
  },
  error => {
    // do something with request error
    return Promise.reject(error)
  }
)


service.interceptors.response.use(
  response => {
    // if the custom code is not 20000, it is judged as an error.
    const res = response.data
    if (res.code == 500){
      Notify({ type: 'danger', message: res.message });
    }
    return response
  },
  error => {
    const res = error.response.data
    if (res.message = "Token失效，请重新登录"){
      Dialog.alert({
        message: 'Token失效，请重新登录！',
        theme: 'round-button',
      }).then(() => {
        Cookies.remove('kaoShi_token')
        Router.push({path: "/"})
      });
    }else {
      Notify({ type: 'danger', message: res.message });
    }
    return Promise.reject(error)
  }
)

export default service
